

var check_email;
$(document).on('pageshow','#addproductnologged', function(event) {


    /**
     * Created by trisatria on 2/21/14.
     */
    //init location
    //init location
    for(var i=0; i< _topic_loc.length ; i = parseInt(i) + 1){
        var content = '<option value="'+i+'" >'+_topic_loc[i]+'</option>';
        if(i == 0){
            $('#topic_location').parent().children('span').text(_topic_loc[i]);
            content = '<option value="'+i+'" selected >'+_topic_loc[i]+'</option>';
        }
        $('#topic_location').append(content);

    }
    //init cat
    for(var i=0; i< _topic_cat.length ; i = parseInt(i) + 1){

        var content = '<option value="'+_topic_cat[i]['id']+'" >'+_topic_cat[i]['title']+'</option>';
        if(_topic_cat[i]['id']== _topic_cat.length ){
            $('#cat_id').parent().children('span').text( _topic_cat[i]['title']);
            content = '<option value="'+_topic_cat[i]['id']+'" selected >'+_topic_cat[i]['title']+'</option>';
        }
        $('#cat_id').append(content);
    }

    $('#addproductnologged #logged').hide();
    $('#addproductnologged .login_form').show();
    //upload product form
    /////click btn upload

   /* $(function ()
    {
        $("#wizard").steps({
            headerTag: "h2",
            bodyTag: "section",
            transitionEffect: "slideLeft",
            onFinished: function(){
                addTopicNoLogged();
            }
        });
    });*/


    $('#btn_upload_product_nologged').click(function(){
        addTopicNoLogged();
    })

    $('#step-2').hide();
    function addTopicNoLogged(){
        //topic
        var title = $('#title').val();
        var price = $('#price').toNumber().val().replace('.','');
        var expire_date = $('#date').val();
        var topic_location =  $('#topic_location').find(":selected").val();
        var cat_id =  $('#cat_id').find(":selected").val();
        var short_description = $('#short_description').val();
        var full_description = $('#full_description').val();
        var topic_type = $('input[name=topic_type]:checked').val();
        var show_price = $('input[name=show_price]:checked').val();
        var is_brandnew = $('input[name=is_brandnew]:checked').val();
        var images = $('#images').val();
        //end topic

        //user
        var email =  $('#email').val();
        var avatar =  $('.thumb_border img').attr('src');
        var name =    $('#addproductnologged #name').val();
        var pass =  $('#addproductnologged #password').val();
        var re_pass =  $('#addproductnologged #re_password').val();
        var add = $('#addproductnologged #add').val();
        var phone = $('#addproductnologged #phone').val();
        var _uid = '';
        var info_user = $.session.get("logged");
        if(typeof  info_user == "undefined"){
            if($('#email_1').val() != '' && $('#name_1').val() != ''){
                email = $('#email_1').val();
                phone = $('#phone_1').val();
                avatar = '';
                name =   $('#name_1').val();
                pass =  '';
                add = '';
                _uid = '';
            }else{
                if(email == '')
                {
                    alert('Chưa Nhập Email');
                    $('#email').addClass('input-error');
                    return false;
                }else{
                    $('#email').removeClass('input-error');
                }
                if(name == '')
                {
                    alert('Chưa Nhập Tên');
                    $('#name').addClass('input-error');
                    return false;
                }
                else{
                    $('#name').removeClass('input-error');
                }
                if(pass == '')
                {
                    alert('Chưa Nhập Password');
                    $('#password').addClass('input-error');
                    return false;
                }
                else{
                    $('#password').removeClass('input-error');
                }
                if(re_pass == '')
                {
                    alert('Chưa Nhập Lại Password');
                    $('#re_password').addClass('input-error');
                    return false;
                }else{
                    $('#re_password').removeClass('input-error');
                }
                if(pass != re_pass){
                    $('#re_password').addClass('input-error');
                    $('#password').addClass('input-error');
                    alert('Mật Khẩu 1 Chưa Khớp Mật Khẩu 2');
                    return false;
                }else{
                    $('#re_password').removeClass('input-error');
                    $('#password').removeClass('input-error');
                }
                if(check_email == true){
                    return false;
                }
            }

        }else{
            info_user = $.parseJSON(info_user);
            _uid = info_user['id'];
            //alert(_uid);
        }
        //alert(info_user);
        //info_user = $.parseJSON(info_user);
        $.ajax({
            url : _host+"topic/addnologged",
            type: "POST",
            data: { topic:{ title: title,
                price: price,
                //expire_date: expire_date,
                topic_location: topic_location,
                cat_id: cat_id,
                short_description: short_description,
                full_description: full_description,
                topic_type: topic_type,
                show_price: show_price,
                is_brandnew: is_brandnew,
                images: '/upload/image/'+images,
                thumb:  '/upload/image/'+images,
                user_id: _uid
            },
                user: {
                    name: name,
                    password: pass,
                    address: add,
                    phone: phone,
                    avatar: avatar,
                    email: email
                }
            }
        }).done(function(data){
            data = $.parseJSON(data);
            var topic_id = data['topic_id'];

            var user_info = data['user'];
            if(topic_id != -1){
                //$('#alert-sucess').show();
                var item_array = new Array();
                $( ".gel_item" ).each(function() {
                    //console.log($(this).attr('src'));
                        var item_data = {};
                        item_data['topic_id'] = topic_id;
                        item_data['user_id'] = user_id;
                        item_data['link'] = $(this).attr('src');
                        item_data['link'] = item_data['link'].replace(_host_img,'');
                        item_array.push(item_data);
                });
                console.log(JSON.stringify(item_array));
                $.cookie("logged",data['user']);
                $.ajax({
                    url : _host+"topic/addgellary",
                    type: "POST",
                    data: {data: JSON.stringify(item_array)}
                });
                $.mobile.changePage('productdetail.html?product_id='+topic_id, {  role: "page", reverse: true } );
            }
        });
    }
    //// end click btn upload
    //end upload product form
});

$(document).on('click','#btn_add_new_slot',function(){

    var slot = '  <div class="ui-grid-a">';
    slot += ' <div class="ui-block-a"><div class="ui-bar ui-bar-a" style="height:60px">';
    slot += '    <a href="#popupNested" data-rel="popup" class="ui-link ui-btn ui-shadow ui-corner-all" data-transition="pop">Chọn Hình Ảnh.</a>';
    slot += '</div></div>';
    slot += '    <div class="ui-block-b"><div class="ui-bar ui-bar-a" style="height:60px">';
    slot += '        <a href="#popupNested" data-rel="popup" class="ui-link ui-btn ui-shadow ui-corner-all" data-transition="pop">Chọn Hình Ảnh.</a>';
    slot += '    </div></div>';
    slot += '</div>';
    $('#row_images').append(slot);
});
$(document).on('click','.gel_item',function(){
    $(this).next().show();
});
$(document).on('click','.img_close', function(){
    $(this).parent().hide();
    $(this).parent().hide();
})
$(document).on('click','.img_del', function(){
    $(this).parent().parent().remove();
    $(this).parent().hide();
})
$(document).on('click','.img_set_thumnail', function(){
    var src = $(this).attr('data_rel');
    $('#images').val(src);

    $('#img_append').children('.col50').removeClass('thumb_border');
    $(this).parent().parent().addClass('thumb_border');
    $(this).parent().hide();
})

$(document).on('click','#btn_next_step', function(){

    var title = $('#title').val();
    var price = $('#price').val();
    var short_description = $('#short_description').val();
    var full_description = $('#full_description').val();
    if(title == ''){
        alert('Chưa Nhập Tiêu Đề Sản Phẩm');
        return false;
    }
    if(price == ''){
        alert('Chưa Nhập Giá Sản Phẩm');
        return false;
    }
    if(short_description == ''){
        alert('Chưa Nhập Miêu Tóm Tắt');
        return false;
    }
    if(full_description == ''){
        alert('Chưa Nhập Chú Thích Sản Phẩm:  ');
        return false;
    }
    $('#step-2').show();
    $('#step-1').hide();
})

$(document).on('click','#btn_prev_step', function(){
    $('#step-1').show();
    $('#step-2').hide();
})
$(document).on('change','#email_1', function(){
    checkemail('#email_1');
});
$(document).on('change','#email',function(){
    checkemail('#email');
});


function checkemail(elem){
    $.mobile.loading('show');
    $.ajax({
        url: _host+'user/checkuserbyemail',
        type: 'GET',
        async: false,
        data: { user_email: $(elem).val() }
    }).done(function(data){
        console.log(data);
        if(data == 1){
            alert('Email này đã có người đăng ký');
            check_email = true;
            $('#email').addClass('input-error');

        }else{
            check_email = false;
            $('#email').removeClass('input-error');
        }
        $.mobile.loading('hide');
        //console.log(data);
    });
}

